/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.jcr;

import java.util.Calendar;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.eventhandler.OnPublishPageEvent;
import org.gidoo.cms.eventhandler.OnPublishResourceEvent;
import org.gidoo.cms.eventhandler.OnRejectPageEvent;
import org.gidoo.cms.eventhandler.OnRejectResourceEvent;
import org.gidoo.cms.helper.Tools;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * Handle publishing of pages.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class PublishDataManager 
{
  
  /**
   * Publish changes.
   * 
   * @param draft The draft node.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean publishPageDraft(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      String path = Tools.draftName2Path(draft.getName());
      Node oldPublished = s.getJcrRootNode().getNode(path);

      // only save if non empty
      if(JcrHelper.isPublished(oldPublished))
      {
        oldPublished.checkin();
        oldPublished.checkout();
      }
      
      JcrHelper.copyPageProperties(draft, oldPublished);

      oldPublished.setProperty("cms:publisher", s.getUsername());

      oldPublished.checkout();

      draft.remove();

      s.getJcrRootNode().save();

      Logger.getLogger(GidooCMS.ACTION_LOG).log(Level.INFO,
        "PUBLISH ACTION: user \"" + s.getUsername() + "\" published " +
        "page " + path);

      ((GidooCMS) s.getApplication()).getEventManager().fireEvent(
        new OnPublishPageEvent(path, s.getUsername()));
      
      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  /**
   * Reject a draft.
   * @param draft The draft.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean rejectPageDraft(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      String draftPath = Tools.draftName2Path(draft.getName());
      Node parent = draft.getParent();
      draft.remove();
      parent.save();

      Logger.getLogger(GidooCMS.ACTION_LOG).log(Level.INFO,
        "REJECT ACTION: user \"" + s.getUsername() + "\" rejected " +
        "page " + draftPath);

      ((GidooCMS) s.getApplication()).getEventManager().fireEvent(
        new OnRejectPageEvent(draftPath, s.getUsername()));

      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }

  /**
   * Publish a newly added rssource.
   * @param draft The newly added resource.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean  publishResource(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      Session jcrSession = s.getJcrSession();
      String path = Tools.draftName2Path(draft.getName());
      if(s.getJcrRootNode().hasNode(path))
      {
        // ups, there is already a node with this path, delete the draft and
        // and inform the user
        s.warn(getI18N(s).getString("resexists"));
        Node parent = draft.getParent();
        draft.remove();
        parent.save();
        return false;
      }
      
      draft.setProperty("cms:publisher", s.getUsername());
      draft.setProperty("jcr:lastModified", Calendar.getInstance());
      
      jcrSession.move(draft.getPath(), "/" + path);
      jcrSession.save();
      
      Logger.getLogger(GidooCMS.ACTION_LOG).log(Level.INFO,
        "PUBLISH ACTION: user \"" + s.getUsername() + "\" published " +
        "resource " + path);

      ((GidooCMS) s.getApplication()).getEventManager().fireEvent(
        new OnPublishResourceEvent(path, s.getUsername()));

      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  /**
   * Rejectt a newly added resource.
   * @param draft The newly added resource.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean rejectResource(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      String draftPath = Tools.draftName2Path(draft.getName());
      Node parent = draft.getParent();
      draft.remove();
      parent.save();
      
      Logger.getLogger(GidooCMS.ACTION_LOG).log(Level.INFO,
        "REJECT ACTION: user \"" + s.getUsername() + "\" rejected " +
        "resource " + draftPath);

      ((GidooCMS) s.getApplication()).getEventManager().fireEvent(
        new OnRejectResourceEvent(draftPath, s.getUsername()));

      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  private static ResourceBundle getI18N(GidooCMSSession session)
  {
    return java.util.ResourceBundle.getBundle("org/gidoo/cms/jcr/I18N", session.getLocale());
  }
  
}
